#include "stdafx.h"
#include "Config.h"

#include "Streams.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace serika
{
	namespace ut
	{
		Config::Config(const Char* filePath)
			: mFilePath(filePath), mModified(false)
		{
			this->m_ini.LoadFile(filePath);
		}

		Config::~Config()
		{
			this->Flush();
		}

		void Config::GetAllKey(const Char* section, std::vector<ut::String>& keys)
		{
			keys.clear();
			CSimpleIni::TNamesDepend names;
			this->m_ini.GetAllKeys(section, names);
			for (CSimpleIni::TNamesDepend::iterator it(names.begin());
				it != names.end(); ++it)
			{
				keys.push_back((it)->pItem);
			}
		}

		const Char* Config::GetString(const Char* section, const Char* key, const Char* def /*= ""*/) const
		{
			return this->m_ini.GetValue(section, key, def);
		}

		int Config::GetInt(const Char* section, const Char* key, int def) const
		{
			const Char* val = this->m_ini.GetValue(section, key);
			if (val == 0)
			{
				return def;
			}

#ifdef _UNICODE
			return _wtoi(val);
#else
			return atoi(val);
#endif
		}

		bool Config::GetBool(const Char* section, const Char* key, bool def) const
		{
			const Char* val = this->m_ini.GetValue(section, key);
			if (val == 0)
			{
				return def;
			}

			ut::String s = val;
			return s != _T("0") && s != _T("false");
		}

		void Config::SetString(const Char *section, const Char *key, const Char *value)
		{
			this->m_ini.SetValue(section, key, value);
			this->mModified = true;
		}

		void Config::SetInt(const Char* section, const Char* key, int value)
		{
			ut::Sstream ss;
			ss.setf(std::ios_base::dec);
			ss << value;
			this->m_ini.SetValue(section, key, ss.str().c_str());
			this->mModified = true;
		}

		void Config::SetBool(const Char* section, const Char* key, bool value)
		{
			this->m_ini.SetValue(section, key, value ? _T("true") : _T("false"));
			this->mModified = true;
		}

		void Config::Flush()
		{
			if (!mModified)
			{
				return;
			}
			//FILE* fp = ::fopen(this->mFilePath.c_str(), "wb");
			//if (fp != 0)
			//{
			//	::fclose(fp);
			//}
			this->m_ini.SaveFile(mFilePath.c_str());
			this->mModified = false;
		}

		float Config::GetFloat( const Char* section, const Char* key, float def /*= 0.0f*/ ) const
		{
			const Char* val = this->m_ini.GetValue(section, key);
			if (val == 0)
			{
				return def;
			}

#ifdef _UNICODE
			return static_cast<float>(_wtof(val));
#else
			return static_cast<float>(atof(val));
#endif
		}

		void Config::SetFloat( const Char* section, const Char* key, float value )
		{
			ut::Sstream ss;
			ss.setf(std::ios_base::dec);
			ss << value;
			this->m_ini.SetValue(section, key, ss.str().c_str());
			this->mModified = true;		
		}
	}
}
